package com.example.springboot.wechat.wechatinterface.controller;

import com.example.springboot.wechat.wechatinterface.entity.dto.WeChatDto;
import com.example.springboot.wechat.wechatinterface.job.TokenCache;
import com.example.springboot.wechat.wechatinterface.util.GsonUtils;
import com.example.springboot.wechat.wechatinterface.util.SDKSignUtils;
import com.example.springboot.wechat.wechatinterface.util.SignUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/wechat")
public class WeChatController {

    private static Logger logger = Logger.getLogger(WeChatController.class);

    @Autowired
    TokenCache tokenCache;

    /**
     * 请求认证
     *
     * @param request
     * @param response
     * @param weChatDto
     */
    @RequestMapping(value = "/signature", method = RequestMethod.GET)
    public void signature(HttpServletRequest request, HttpServletResponse response, WeChatDto weChatDto) {
        try {
            if (SignUtil.checkSignature(weChatDto.getSignature(), weChatDto.getTimestamp(), weChatDto.getNonce())) {
                PrintWriter out = response.getWriter();
                out.print(weChatDto.getEchostr());
                out.close();
            } else {
                logger.info("非法请求地址！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信首次请求认证异常：", e);
        }
    }

    /**
     * 获取全局网页token
     */
    @RequestMapping(value = "getToken", method = RequestMethod.GET)
    @ResponseBody
    public String getToken(HttpServletRequest request, HttpServletResponse response, WeChatDto weChatDto) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            String access_token = tokenCache.getCache("access_token");
            map.put("access_token", access_token);
            logger.info("获取全局网页token: "+access_token);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信获取全局网页token异常：", e);
        }
        String json = GsonUtils.parseBeanToJson(map);
        return json;
    }

    /**
     * 获取网页token
     */
    @RequestMapping(value = "getWebToken", method = RequestMethod.GET)
    @ResponseBody
    public String getWebToken(HttpServletRequest request, HttpServletResponse response, WeChatDto weChatDto) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            String url = "";
            String jsapi_ticket = tokenCache.getCache("jsapi_ticket");
            map.put("jsapi_ticket", jsapi_ticket);
            logger.info("获取网页token: "+jsapi_ticket);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信获取网页token异常：", e);
        }
        String json = GsonUtils.parseBeanToJson(map);
        return json;
    }

    /**
     * 获取网页签名
     */
    @RequestMapping(value = "getWebSignature", method = RequestMethod.GET)
    @ResponseBody
    public String getWebSignature(HttpServletRequest request, HttpServletResponse response, WeChatDto weChatDto) {
        Map<String, String> map = new HashMap<String, String>();
        try {
//            签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。
//            签名用的url必须是调用JS接口页面的完整URL。
            String access_token = tokenCache.getCache("access_token");
            String jsapi_ticket = tokenCache.getCache("jsapi_ticket");
            map =  SDKSignUtils.sign(jsapi_ticket,weChatDto.getWebUrl());
            logger.info("获取网页签名: "+map.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信web端签名认证异常：", e);
        }
        String json = GsonUtils.parseBeanToJson(map);
        return json;
    }

}